package com.sxkf.template.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxkf.template.entity.CommentLike;
import com.sxkf.template.entity.Post;
import com.sxkf.template.entity.PostComment;
import com.sxkf.template.entity.PostNotice;
import com.sxkf.template.mapper.PostCommentMapper;
import com.sxkf.template.mapper.PostMapper;
import com.sxkf.template.mapper.PostNoticeMapper;
import com.sxkf.template.service.CommentLikeService;
import com.sxkf.template.service.PostCommentService;
import com.sxkf.template.vo.response.PostCommentVo;
import org.jeecg.common.exception.SxkfException;
import org.jeecg.common.util.CheckEmptyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 帖子评论 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-08-20 11:48:57
 */
@Service
public class PostCommentServiceImpl extends ServiceImpl<PostCommentMapper, PostComment> implements PostCommentService {
    @Resource
    private PostMapper postMapper;
    @Resource
    private PostNoticeMapper postNoticeMapper;

    @Resource
    private CommentLikeService commentLikeService;

    @Override
    public void add(PostComment postComment) {
        //保存评论
        save(postComment);
        //动态评论量+1
        postMapper.addCommentCount(postComment.getPostId());
        //添加动态通知

        PostNotice postNotice = new PostNotice();
        postNotice.setPostId(postComment.getPostId());
        String pictureJson = postMapper.selectById(postComment.getPostId()).getPictureJson();
        if (CheckEmptyUtil.isNotEmpty(pictureJson)){
            postNotice.setPostPicture(pictureJson.split(",")[0]);
//            List<String> pics = JSON.parseArray(pictureJson, String.class);
//            if (!pics.isEmpty()){
//                postNotice.setPostPicture(pics.get(0));
//            }
        }
        postNotice.setUserId(postComment.getUserId());
        postNotice.setUserAvater(postComment.getUserAvater());
        postNotice.setUserNickName(postComment.getUserNickName());
        postNotice.setNote(postComment.getContent());
        postNotice.setType("2");
        postNotice.setCommentId(postComment.getId());
        postNotice.setState("0");
        postNoticeMapper.insert(postNotice);
    }

    @Override
    public Page<PostCommentVo> myComment(Integer pageNo, Integer pageSize, Long userId) {

        Page<PostComment> page = page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<PostComment>()
                .eq(PostComment::getUserId, userId));

        List<PostComment> postCommentList = page.getRecords();

        List<String> postIdList = postCommentList.stream().map(PostComment::getPostId).collect(Collectors.toList());

        List<Post> posts = postMapper.selectList(new LambdaQueryWrapper<Post>().in(Post::getId, postIdList));

        Map<String, Post> postMap = posts.stream().collect(Collectors.toMap(Post::getId, post -> post));

        Page<PostCommentVo> commentVoPage = new Page<>(pageNo, pageSize);
        ArrayList<PostCommentVo> postCommentVoList = new ArrayList<>();
        PostCommentVo postCommentVo = new PostCommentVo();
        page.getRecords().forEach(item -> {
            BeanUtils.copyProperties(item, postCommentVo);
            postCommentVo.setPostPicture(postMap.get(item.getPostId()).getPictureJson().split(",")[0]);
            postCommentVoList.add(postCommentVo);
        });
        commentVoPage.setRecords(postCommentVoList);

        return commentVoPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String likeById(CommentLike commentLike) {

        if (CheckEmptyUtil.isEmpty(commentLike.getUserId())){
            throw new SxkfException("点赞的用户id为空");
        }

        if (CheckEmptyUtil.isEmpty(commentLike.getCommentId())){
            throw new SxkfException("被点赞评论id为空");
        }

        CommentLike one = commentLikeService.getOne(new LambdaQueryWrapper<CommentLike>()
                .eq(CommentLike::getUserId, commentLike.getUserId())
                .eq(CommentLike::getCommentId, commentLike.getCommentId())
                .eq(CommentLike::getType, "1")
        );

        if (CheckEmptyUtil.isEmpty(one)){
            commentLike.setType("1");
            commentLikeService.save(commentLike);
            update(new LambdaUpdateWrapper<PostComment>()
                    .setSql("like_count = like_count - 1")
                    .eq(PostComment::getId, commentLike.getId())
            );
            return "点赞成功";
        }

        commentLikeService.removeById(one);
        update(new LambdaUpdateWrapper<PostComment>()
                .setSql("like_count = like_count + 1")
                .eq(PostComment::getId, commentLike.getId())
        );

        return "取消点赞";
    }

    @Override
    public Boolean isLike(String userId, String type, String commentId) {
        CommentLike one = commentLikeService.getOne(new LambdaQueryWrapper<CommentLike>()
                .eq(CommentLike::getUserId, userId)
                .eq(CommentLike::getCommentId, commentId)
                .eq(CommentLike::getType, type)
        );
        return !CheckEmptyUtil.isEmpty(one);
    }
}
